<template>
    <div class="px-[100px]">
        <div>全部商品</div>
        <div v-if="cartList.length">
            <CartItem
                v-for="item in cartList"
                :id="item.id"
                :name="item.goodsName"
                :img="item.goodsImg"
                :price="item.goodsPrice"
                :spec="item.goodsSpec"
                v-model:num="item.goodsNum"
                @change-num="handleNumChange(item)"
                @delete="handleDelete"
                v-model:checked="item.checked"
            ></CartItem>
        </div>
        <div v-else>
            <el-empty description="暂无数据" />
        </div>
        <div
            class="fixed bottom-[20px] border-t-2 border-gray-200 left-[100px] right-[100px] flex justify-between h-[60px] items-center"
        >
            <el-checkbox v-model="checkAll" label="全选" size="large" @change="handleAll" />
            <div class="flex items-center">
                <div class="text-lg text-orange-600">共￥{{ totalPrice }}</div>
                <el-button class="ml-8" type="primary" size="large" @click="submitOrder">下单</el-button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import CartItem from '@/components/CartItem.vue'
import { delCart, getCartList, updateCart } from '@/apis/cart'
import { computed, onMounted, ref } from 'vue'
import { addCartOrder } from '@/apis/order'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
const checkAll = ref(false)
const cartList = ref([])
const totalPrice = computed(() => {
    return cartList.value
        .filter((item) => item.checked)
        .map((item) => item.goodsPrice * item.goodsNum)
        .reduce((a, b) => a + b, 0)
})
const getList = async () => {
    const res = await getCartList({
        pageNum: 1,
        pageSize: 1000
    })
    cartList.value = res.list.map((item) => {
        return {
            ...item,
            checked: false
        }
    })
}
const handleNumChange = async (item) => {
    await updateCart({
        id: item.id,
        goodsId: item.goodsId,
        goodsNum: item.goodsNum
    })
}
const handleDelete = async (val) => {
    await delCart(val)
    getList()
}
const handleAll = (val) => {
    if (val) {
        cartList.value.forEach((item) => (item.checked = true))
    } else {
        cartList.value.forEach((item) => (item.checked = false))
    }
}
const submitOrder = async () => {
    const ids = cartList.value.filter((item) => item.checked).map((item) => item.id)
    if (ids.length) {
        await addCartOrder(ids)
        router.push({
            name: 'OrderEdit',
            query: {}
        })
    } else {
        ElMessage.error('未选择商品')
    }
}
onMounted(() => {
    getList()
})
</script>

<style scoped></style>
